# -*- coding:utf-8 -*-
import json
from ctypes import pythonapi

import requests
import pymysql
from fontTools.ttLib import TTFont


class Spider:
    def get_data(self, url):
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
        }
        new_map = {'&#57808;': 7, '&#58149;': 4, '&#58397;': 1, '&#58670;': 9, '&#58928;': 2}
        headers = {}
        new_map = {'&#57808;': 7, '&#58149;': 4, '&#58397;': 1, '&#58670;': 9, '&#58928;': 2, '&#59246;': 8, '&#59537;': 5, '&#59854;': 0, '&#60146;': 3, '&#60492;': 6}

        response = requests.get(url, headers=headers).text

        # 全局替换
        for key, value in new_map.items():
            if key in response:
                response = response.replace(key, str(value))

        resp = json.loads(response)
        postList = resp.get("data").get("postList")
        for item in postList:
            print(item)
            name = item['title']
            price = item['price']
            mileage = item['road_haul']
            years = item['license_date']
            image = item['thumb_img']
            first_price = item['first_pay']
            car_service = ''
            self.save_data(name, price, mileage, years, image, first_price, car_service)
            print("保存成功====>" + name)

    def save_data(self, name, price, mileage, years, image, first_price, car_service):
        '''
        保存数据
        :param content:
        :return:
        '''
        # 创建连接
        db = pymysql.connect(host="47.98.194.238", user="root", password="liankazdzq2022", database="cars",
                             charset="utf8")
        cur = db.cursor()

        # 保存数据
        sql = "insert into cars(name,price,mileage,years,image,first_price,car_service)values ('%s','%s','%s','%s','%s','%s','%s')" % (
            name, price, mileage, years, image, first_price, car_service)
        print("sql:" + sql)
        # 执行sql
        cur.execute(sql)
        # sql提交
        db.commit()
        # 关闭连接
        cur.close()
        db.close()

    def get_font_map(self, d={}):
        font_relation_map = {
            'uniE9CE': 0,
            'uniE41D': 1,
            'uniE630': 2,
            'uniEAF2': 3,
            'uniE325': 4,
            'uniE891': 5,
            'uniEC4C': 6,
            'uniE1D0': 7,
            'uniE76E': 8,
            'uniE52E': 9
        }
        """
          获取字体映射关系
          :return:
          """
        font = TTFont(r'gzfont4.woff2')

        # 字体文件转为xml文件
        # font.saveXML(r"font.xml")

        font_map = font.getBestCmap()
        font.close()

        # print(font_map)

        new_font_map = d

        # 遍历字典，重新组成一个新的映射字典
        for index, key in enumerate(font_map):
            value = font_map[key]

            # 捕获异常
            try:
                temp = font_relation_map[value]
            except:
                temp = ''
            if temp != '':
                # 根据响应结果中字体反爬数据格式，将键值前面添加字符串&#，用于匹配
                new_font_map['&#' + str(key) + ";"] = temp

        return new_font_map


if __name__ == '__main__':
    # python的创建对象
    spider = Spider()
    # print(spider.get_font_map())
    for i in range(1, 100):
        url = ("https://mapi.guazi.com/car-source/carList/pcList?versionId=0.0.0.0&sourceFrom=wap&deviceId=a2ae5dab-6ef1-41ff-8e06-e82939f72609&osv=Windows+10&minor=&sourceType=&ec_buy_car_list_ab=&location_city=&district_id=&tag=-1&license_date=&auto_type=&driving_type=&gearbox=&road_haul=&air_displacement=&emission=&car_color="
               "&guobie=&bright_spot_config=&seat=&fuel_type=&order=&priceRange=0,-1&tag_types=&diff_city=&intention_options=&initialPriceRange=&monthlyPriceRange=&transfer_num=&car_year=&carid_qigangshu=&carid_jinqixingshi=&cheliangjibie=&page={}&pageSize=20&city_filter=12&city=12&guazi_city=12&qpres=663591784211505152&platfromSource=wap").format(
            i)
        spider.get_data(url)
